import { defineStore } from 'pinia';
import { postAction } from '@/utils/request';
import _ from 'lodash'
import { useDict } from '@/utils/dict';
import { getJsonSetting } from '@/utils/api';


//simple const vars
const portsSql = `SELECT country,city,code,port_type,id from yg_cityCode_view order by 1`
const clientSql = `select id,name,id as value,name as label,profit,paid_amount,total,unpaid_amount,income,expenditure,invoice_amount from "YG_client" order by name`
const tradePartnerSql = `select group_type,c.name,p.id,bill_type,fee_items,id_company,c.name as title,id_client from "YG_TradePartner" p join "YG_client" c on c.id=p.id_client order by group_type,p.id`
const companiesSql = "select dept_id as value, dept_name as label from sys_dept where parent_id=100"
const feeTypesSql = `select id,code as value,name as label from "YG_FeeType"`
const url = {
    getDataBySql: '/sys/getDataBySql',
    asyncDataBySql: '/sys/asyncDataBySql',
    template: '/yg/template',
    exportXlsForCheckBills: '/yg/exportXlsForCheckBills',
}

// 相同业务逻辑下，常用函数和变量实现共用
export const useCheckBillStore = defineStore('checkBill', {
    // state 用于存储状态
    state: () => ({
        name: '张三',
        age: 25,
        isLoggedIn: false,
        ports: [],
        clients: [],
        tradePartners: [],
        groupedTradePartners: [],
        tradePartnerObj: {},
        companies: [],
        feeTypes: [],
        feeTypeById: {},
        feeTypeObj: {},
        companyObj: {},
        dictObj: {}
    }),
    // getters 用于计算状态，类似于组件的计算属性
    getters: {
        // companyObj: (state)=> {
        //     let obj = {}
        //     state.companies.forEach((c)=> obj[c.value] = c.label)
        //     return obj;
        // },
    },
    // actions 用于修改状态，支持同步和异步操作
    actions: {
        initWatch() {
            // 使用 $subscribe 监听状态变化
            this.$subscribe((mutation, state) => {
            });
        },
        setDict(_key, value) {
            if (_key !== null && _key !== "") {
                this.dictObj[_key] = value
                //console.error("this.dict", JSON.stringify(this.dictObj))
            }
        },
        // 删除字典
        removeDict(_key) {
            let bln = false;
            try {
                this[_key]=[];
                bln = true;
            } catch (e) {
                bln = false;
            }
            return bln;
        },
        getTradePartner(){
            if (this.groupedTradePartners && this.groupedTradePartners.length>0) return
            postAction(url.getDataBySql,{sql: tradePartnerSql}).then(res=>{
                if(res && res.success && _.isArray(res.data)){
                    if(res.data){
                        // res.data.forEach((d)=>{
                        //     d.id_client = parseInt(d.id_client)
                        //     d.id_company = parseInt(d.id_company)
                        // })
                        this.tradePartners = res.data
                        //更新相关联动
                        let tmp1 = {}, tmp2 = {}, arr1 = [], tmp3 = {};
                        res.data.forEach(r=>{
                            if (!tmp1[r.group_type]) tmp1[r.group_type] = [];
                            tmp1[r.group_type].push(r);
                            let fullname = `${r.group_type}<br/>${r.title}`
                            tmp2[r.id] = {...r, fullname};
                            tmp3[r.id] = fullname.replace("<br/>","-")
                        })
                        for(let i in tmp1){
                            arr1.push({
                                label: i,
                                options: tmp1[i].map(r=>{
                                    return { label: `${i}-${r.name}`, value: r.id, bill_type: r.bill_type }
                                })
                            })
                        }
                        this.groupedTradePartners = arr1;
                        this.tradePartnerObj = tmp2;
                        this.setDict("id_trade_partner", tmp3)
                    }
                }
            })
        },
        getPortsAndClient(){
            if (this.ports && this.clients && this.ports.length>0 && this.clients.length>0) return
            postAction(url.asyncDataBySql,{sqls: [portsSql,clientSql]}).then(res=>{
                if(res && res.success && _.isArray(res.data)){
                    [this.ports, this.clients] = res.data
                }
                let clientsObj = {}
                this.clients.forEach((c)=>{
                    clientsObj[c.value] = c.label
                })
                this.setDict("id_client", clientsObj)
            })
        },
        getMyCompanies(){
            if(this.companies && this.companies.length>0) return
            if(!this.companies || this.companies.length===0)
                postAction(url.asyncDataBySql,{sqls: [companiesSql]}).then(res=>{
                    if(res && res.success && _.isArray(res.data)){
                         let [ companies  ] = res.data
                         companies.forEach((c)=>{
                            c.value = c.value+""
                            this.companyObj[c.value] = c.label
                         })
                         this.setDict("id_company", this.companyObj)
                         this.companies = companies
                    }
                })
        },
        getFeeTypes(){
            if(this.feeTypes && this.feeTypes.length>0) return
            postAction(url.getDataBySql,{sql: feeTypesSql}).then(res=>{
                if(res && res.success && _.isArray(res.data)){
                    this.feeTypes = res.data
                    //更新相关联动
                    let obj1 = {}, obj2 = {};
                    res.data.forEach((c)=> {
                        obj1[c.value] = c.label
                        obj2[c.id] = c
                    })
                    this.feeTypeById = obj2
                    this.feeTypeObj = obj1
                }
            })
        },
        getColumnSettings(keys){
            if(!_.isArray(keys)) keys = [keys]
            keys.forEach(key => {
                if (this.dictObj[key]) return
                getJsonSetting({
                    type: 'columns_layout',
                    key: key
                }).then(res => {
                    if (res && res.success) {
                       if( res.data && res.data.length > 0) this.setDict(key, res.data)
                    }
                })
            })
        }
    }
});

export default useCheckBillStore